#coding=utf-8
'''
Created on 2011-3-26

@author: zarra
'''
import re
from datetime import datetime
pattern = r'([0-9a-fA-F]{4,4}),([0-9a-fA-F]{4,4})'
p=re.compile(pattern)
def convert_key(str):
    '''
    将'(XXXX,XXXX)'形式的字符串转换成 两个整数
    '''
    m=p.search(str)
    if m!=None:
        return map(lambda s:int(s,16), m.groups())
    else:
        return None,None
    
def gen_python_dict(stream):
    '''
    根据 dicom-dict.txt 文件 生成 Python的数据字典
    '''
    result ={}
    line = stream.readline()
    while len(line)> 0:
        if not line.startswith('#'):
            fields = line.split('\t')
            key_h,key_l = convert_key(fields[0])
            try:
                #print line
                size=int(fields[3])
            except ValueError,e:
                size=-1
            result[(key_h,key_l)]={'type':fields[1],'title':fields[2],'size':size}
        line = stream.readline()
    return result
        
def init(filename):
    with open(filename,'r') as f:
        return gen_python_dict(f) 
def dump2python(d,stream):
    now = datetime.now().strftime('%Y%m%d_%H:%M:%S')
    stream.write('''#!/usr/bin/env python
#coding=utf-8
\'\'\'
This file is auto create by dicom_tools!
%s
\'\'\'
__dicom_dict__={\n'''%now)
    template ='''\t(0x%04x,0x%04x):{'type':'%s','title':'%s','size':%d},\n'''  
    keys =d.keys()
    keys.sort()
    for k in keys:
        v=d[k]
        if k[0]!=None:
            s=template%(k[0],k[1],v['type'],v['title'],v['size'])
            stream.write(s)
    stream.write('}')    
        
if __name__ == '__main__':
    filename = r'../data/dicom-dict.txt'
    f=file(filename)
    d =  gen_python_dict(f)
    with file('./miniDicom_meta.py','w') as stream:
        dump2python(d, stream)

    